#include "command.h"
#include <QAbstractSocket>
#include <QTcpSocket>
#include <QDebug>
#include <QHostAddress>

#define TIME_OUT 500
#define MAX_READ_BUFFER_SIZE 100000

Command::Command()
{
}

Command::~Command()
{
}

bool CommandSock::isConnAlive()
{
    return !(opClient == NULL);
}

void CommandSock::slotConnectOperateServer(const char *ipaddr, int port)
{
    opClient = new QTcpSocket();
    connect(opClient, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(slotStateChanged(QAbstractSocket::SocketState)));
    opClient->connectToHost(ipaddr, port);
    if (!opClient->waitForConnected(TIME_OUT * 5)) {//wait 2500ms
        slotConnectError(opClient->error());
        this->slotDisconnectOperateServer();
        return;
    }
    qDebug() << "Connected to " << opClient->peerAddress().toString() << ":" << opClient->peerPort() << "sta: " << QString("%1").arg(opClient->state());
}

void CommandSock::slotSendOperateData(QByteArray &data)
{
    opClient->write(data);
    opClient->waitForBytesWritten(TIME_OUT * 2);
    opClient->flush();
}

void CommandSock::slotDisconnectOperateServer(void)
{
    if (!opClient)
        return;
    //disconnect(opClient, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(slotConnectError(QAbstractSocket::SocketError)));
    opClient->close();
    opClient->deleteLater();
    opClient = NULL;
}

void CommandSock::slotReceiveData(QByteArray*data, unsigned int mSec)
{
    opClient->waitForReadyRead(mSec);
    (*data) = opClient->readAll();
}

void CommandSock::slotConnectError(QAbstractSocket::SocketError err)
{
    qDebug() << "CommandSock connection error occured" << err;
    switch (err)
    {
    case QAbstractSocket::ConnectionRefusedError:
        qDebug() << "Connecting refused";
        emit error("Connecting refused by server, retrying ()...");
        break;

    case QAbstractSocket::RemoteHostClosedError:
        qDebug() << "Server closed the connection !";
        emit error("Server closed the connection !");
        break;

    case QAbstractSocket::HostNotFoundError:
        qDebug() << "Server not found";
        emit error (QString ("Server not found, host name:"));
        break;

    default:
        qDebug() << "Connection to server is broken";
        emit error("Connection to server is broken !");
        break;
    }
}

void CommandSock::slotStateChanged(QAbstractSocket::SocketState newSta)
{
    qDebug() << "Socket state: " << newSta;
    if (newSta == QAbstractSocket::ClosingState || newSta == QAbstractSocket::UnconnectedState) {
        emit error("Close");
    }
}

